package io.gitee.zkool.barcodegun.pc.ws;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.net.NetUtil;
import io.gitee.zkool.barcodegun.pc.utils.TypingRobot;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.awt.*;
import java.net.InetSocketAddress;

/**
 * @author zhaokk
 * @since 2024/1/31
 */
public class WsServer extends WebSocketServer {

    private static Logger log = LoggerFactory.getLogger(WsServer.class);

    // 默认端口
    public static final int WS_PORT = 2024;

    public WsServer() {
        super(new InetSocketAddress(WS_PORT));
    }

    public WsServer(int port) {
        super(new InetSocketAddress(port));
    }

    public WsServer(InetSocketAddress address) {
        super(address);
    }

    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        // 连接的时候触发的代码
        // This method sends a message to the new client
        conn.send("Welcome to the server!");
        String remoteHostAddress = conn.getRemoteSocketAddress().getAddress().getHostAddress();
        // This method sends a message to all clients connected
        broadcast("new connection: " + remoteHostAddress);
        //用户加入
        userJoin(conn, remoteHostAddress);
        log.info("终端[" + remoteHostAddress + "]已连接!");
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        //断开连接时候触发代码
        userLeave(conn);
        log.info("终端[" + conn.getRemoteSocketAddress().getAddress().getHostAddress() + "]已断开连接!" + reason);
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        String msg = "服务端接收到终端[" + conn.getRemoteSocketAddress().getAddress().getHostAddress() + "]的消息:"+message;
        log.info(msg);
        WsUtil.sendMessageToUser(conn,msg);
        try {
            message = message.replace("，", ",");
//            KeyboardInputUtil.stringInput(message);
            TypingRobot typingRobot = new TypingRobot();
            typingRobot.type(message+"\n");
        } catch (AWTException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onError(WebSocket conn, Exception ex) {
        //错误时候触发的代码
        log.error("终端[" + conn.getRemoteSocketAddress().getAddress().getHostAddress() + "]发生错误!" + ExceptionUtil.stacktraceToString(ex, 500));
        ex.printStackTrace();
        if (conn != null) {
            // some errors like port binding failed may not be assignable to a specific
        }
    }

    @Override
    public void onStart() {
        log.info("\n----------------------------------------------------------\n" +
                "Server started! Access URLs:\n" +
                "ws://" + NetUtil.getLocalhostStr() + ":" + this.getPort() + "\n" +
                "----------------------------------------------------------"
        );
        setConnectionLostTimeout(0);
        setConnectionLostTimeout(100);
    }

    /**
     * 去除掉失效的websocket链接
     * @param conn
     */
    private void userLeave(WebSocket conn){
        WsUtil.removeUser(conn);
    }

    /**
     * 将websocket加入用户池
     * @param conn
     * @param userName
     */
    private void userJoin(WebSocket conn,String userName){
        WsUtil.addUser(userName, conn);
    }

}
